public class PercolationStats {

  private double[] experiments;
  double mean;
  double stddev;
  double hi_conf_int;
  double lo_conf_int;

  /** perform T independent computational experiments on an N-by-N grid */
  public PercolationStats(int N, int T) {
    experiments = new double[T];

    for(int i = 0; i < T; i++) {
      Percolation percolation = new Percolation(N);
      experiments[i] = percolation.experiment();
      StdOut.printf("experiments[%d]\t= %f\n", i, experiments[i]);
    }

    mean = mean();
    stddev = stddev();
    hi_conf_int = confidenceHi();
    lo_conf_int = confidenceLo();
  } 

  /** sample mean of percolation threshold */
  public double mean() {
    double sum = 0;

    for(int i = 0; i < experiments.length; i++) {
      sum += experiments[i];
    }

    return sum / experiments.length;
  } 

  /** sample standard deviation of percolation threshold */              
  public double stddev() {
    double sum = 0;

    StdOut.printf("experiments.length\t= %d\n", experiments.length);

    for(int i = 0; i < experiments.length; i++) {
      sum += Math.pow(experiments[i] - mean, 2);
      StdOut.printf("sum\t= %f\n", sum);
    }

    double powered_sigma  = sum / (experiments.length - 1);
    StdOut.printf("powered_sigma\t= %f\n", powered_sigma);
    return Math.sqrt(powered_sigma);
  } 

  /** returns lower bound of the 95% confidence interval */          
  public double confidenceLo() {
    return mean - (1.96*stddev / Math.sqrt(experiments.length));
  } 

  /** returns upper bound of the 95% confidence interval */    
  public double confidenceHi() {
    return mean + (1.96*stddev / Math.sqrt(experiments.length));
  } 

  /** test client, described below */   
  public static void main(String[] args) {

    PercolationStats percolation_stats = new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1]));

    double mean = percolation_stats.mean;
    double stddev = percolation_stats.stddev;
    double lo_conf_int = percolation_stats.lo_conf_int;
    double hi_conf_int = percolation_stats.hi_conf_int;

    StdOut.printf("mean\t= %f\n", mean);
    StdOut.printf("stddev\t= %f\n", stddev);
    StdOut.printf("95%% confidence interval\t= %f, %f\n", lo_conf_int, hi_conf_int);

    // mean                    = 0.5929934999999997
    // stddev                  = 0.00876990421552567
    // 95% confidence interval = 0.5912745987737567, 0.5947124012262428
  }   
}